package com.relife.sys.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.relife.common.bean.ExcelParam;
import com.relife.common.model.ClientManager;
import com.relife.common.utils.DateUtil;
import com.relife.common.utils.StringUtil;
import com.relife.core.easyui.Easyui;
import com.relife.core.entity.CodeEntity;
import com.relife.core.utils.ExcelUtil;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;


@Controller
@RequestMapping("sys/excel")
public class ExcelController extends BaseController {
	/***
	 * 
	 * @author WU
	 * @date 2016年1月19日 上午11:32:03
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/exportExcel")
	public <T> void exportExcel(HttpServletRequest request, HttpServletResponse response) {
		String tagId = request.getParameter("tagId");
		ExcelParam ep = ExcelUtil.getExcelParam(tagId);
		String title = DateUtil.getTime(DateUtil.YYYYMMDDHHMMSS, new Date()) + StringUtil.getRandom(4) + ".xls";
		try {
			title = new String((ep.getSheetName() + ".xls").getBytes("GBK"), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("content-disposition", "attachment;filename=" + title);

		OutputStream os = null;
		WritableWorkbook work = null;
		try {
			os = response.getOutputStream();
			work = Workbook.createWorkbook(os);
			WritableSheet sheet = work.createSheet(ep.getSheetName(), 0);
			SheetSettings ss = sheet.getSettings();
			ss.setVerticalFreeze(1);// 冻结表头

			// 创建单元格样式(标题样式)
			WritableFont font1 = new WritableFont(WritableFont.createFont("微软雅黑"), 10, WritableFont.BOLD);
			WritableCellFormat wcf = new WritableCellFormat(font1);
			wcf.setAlignment(Alignment.CENTRE); // 平行居中
			wcf.setBorder(Border.ALL, BorderLineStyle.THIN);
			wcf.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
			wcf.setAlignment(Alignment.CENTRE);

			// 创建单元格样式(普通单元格)
			WritableFont font = new WritableFont(WritableFont.createFont("微软雅黑"), 9, WritableFont.NO_BOLD);
			WritableCellFormat wcf1 = new WritableCellFormat(font);
			wcf1.setAlignment(Alignment.CENTRE); // 平行居中
			wcf1.setBorder(Border.ALL, BorderLineStyle.THIN);
			wcf1.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
			wcf1.setAlignment(Alignment.CENTRE);

			List<?> list = null;
			if (ep.isQbc()) {
				list = service.getList(ep.getQbc());
			} else {
				list = service.getList(ep.getSql(), ep.getParam() == null ? null : ep.getParam().toArray());
			}
			if (list != null) {
				for (int i = 0; i < ep.getCells().size(); i++) {
					sheet.addCell(new Label(i, 0, ep.getCells().get(i).getName(), wcf));
					for (int j = 0; j < list.size(); j++) {
						Object value = null;
						if (ep.isQbc()) {
							value = Easyui.getValue(list.get(j), ep.getCells().get(i).getField());
						} else {
							value = ((Map<String, Object>) list.get(j)).get(ep.getCells().get(i).getField());
						}
						if (StringUtil.isNotEmpty(ep.getCells().get(i).getCode())) {
							String val = value == null ? "" : value.toString();
							CodeEntity code = ClientManager.getInstance().getCode(ep.getCells().get(i).getCode(), val);
							if (code != null) {
								value = code.getName();
							}

						} else if (StringUtil.isNotEmpty(ep.getCells().get(i).getJson())) {
							JSONObject obj = JSONObject.parseObject(ep.getCells().get(i).getJson());

							if (obj.containsKey(StringUtil.isEmpty(value) ? "" : value.toString())) {
								value = obj.get(StringUtil.isEmpty(value) ? "" : value.toString());
							}
						}
						sheet.addCell(new Label(i, j + 1, StringUtil.isEmpty(value) ? "" : value.toString(), wcf1));
					}
				}
			}
			// 写入Exel工作表
			work.write();
			// 关闭Excel工作薄对象

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				work.close();
				// 关闭流
				os.flush();
				os.close();
				os = null;
			} catch (Exception e) {

			}
		}

	}
}
